-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSplay Tree - Implementation & Insertion.cpp
100 lines (90 loc) · 2.64 KB
/
Splay Tree - Implementation & Insertion.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <iostream>
using namespace std;
struct NODE {
int key;
NODE *left;
NODE *right;
};
NODE *createNode(int key){
NODE *node = new NODE;
node->key = key;
return node;
}
NODE *sPlay(NODE *root, int key){
if(root == NULL){
return 0;
} else if(!root->left && !root->right || key == root->key) {
return root;
} else if((root->left && key == root->left->key) || (root->left && key < root->left->key && root->left->left == NULL)){
NODE *subtree = root->left;
root->left = NULL;
NODE *temp = subtree->right;
subtree->right = root;
subtree->right->left = temp;
return subtree;
} else if((root->right && key == root->right->key) || (root->right && key > root->right->key && root->right->right == NULL)){
int num = root->key;
NODE *subtree = root->right;
root->right = NULL;
NODE *temp = subtree->left;
subtree->left = root;
subtree->left->right = temp;
return subtree;
} else if(key < root->key){
root->left = sPlay(root->left , key);
} else if(key > root->key){
root->right = sPlay(root->right, key);
}
root = sPlay(root, key);
return root;
}
NODE *insert(NODE *root, int key){
if(!root) return createNode(key);
if(key < root->key){
NODE *num = root;
root->left = insert(root->left, key);
root = sPlay(root, root->left->key);
} else if(key > root->key) {
root->right = insert(root->right, key);
root = sPlay(root, root->right->key);
}
return root;
}
void inorder(NODE *root){
if(!root) return;
inorder(root->left);
cout << root->key << " => ";
inorder(root->right);
}
void print(NODE *root, string indent = "", bool right = true){
if (root != nullptr) {
cout << indent;
if(right){
cout << (indent.length() == 0 ? "Root╌" : "R╌╌╌╌");
indent += " ";
} else {
cout << "L╌╌╌╌";
indent += "┆ ";
}
cout << "[" << root->key << "]" << endl;
print(root->left, indent, false);
print(root->right, indent, true);
}
}
int main(){
int A[] = {15, 10, 17, 7, 13, 16, 14};
int n = sizeof(A)/sizeof(A[0]);
NODE *root = NULL;
for(int i = 0; i < n; i++){
if(i == 0){
root = insert(root, A[i]);
} else {
root = insert(root, A[i]);
}
}
cout << "Print the tree ↴ " << endl;
cout << "-----------------" << endl;
print(root);
cout << endl << endl << "Traverse the tree ↴ " << endl << "Inorder: ";
inorder(root);
}